<template>
  <Modal
    v-model="showOrganizeTestcaseModal"
    :title="projectTestsuiteName"
    :mask-closable="false"
    :closable="false"
    fullscreen
    @on-cancel="handleOrganizeTestcaseCancel"
  >
    <Card title="用例源" :dis-hover="true">
      <div slot="extra">
        <Button
          size="small"
          type="primary"
          icon="ios-search"
          class="card-extra-item"
          @click="search"
          >查询</Button
        >
        <Button
          size="small"
          type="default"
          icon="ios-refresh"
          class="card-extra-item"
          @click="reset"
          >重置</Button
        >
        <Button
          size="small"
          type="text"
          :icon="showMore ? 'ios-arrow-up' : 'ios-arrow-down'"
          class="card-extra-item"
          @click="showMore = !showMore"
          >{{ showMore ? "收起" : "展开" }}</Button
        >
      </div>
      <CollapseTransition>
        <div v-show="showMore">
          <Form label-position="right" :label-width="100" :model="searchParams">
            <Row type="flex" justify="end" :gutter="10">
              <Col span="9">
                <FormItem label="接口所属模块">
                  <SelectTree
                    v-model="searchParams.module"
                    :treeData="moduleSelectTreeData"
                    @on-select-change="selectChangeModule"
                  ></SelectTree>
                </FormItem>
              </Col>
              <Col span="6">
                <FormItem label="请求接口">
                  <Select
                    v-model="searchParams.api"
                    clearable
                    multiple
                    filterable
                    transfer
                    :max-tag-count="1"
                    size="default"
                    @on-select="selectChangeApi"
                  >
                    <Option
                      v-for="item in apis"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </Select>
                </FormItem>
              </Col>
              <Col span="5">
                <FormItem label="用例名称">
                  <Input
                    clearable
                    placeholder="请输入用例名称"
                    v-model="searchParams.name"
                  />
                </FormItem>
              </Col>
              <Col span="4">
                <FormItem label="用例创建人">
                  <Select
                    v-model="searchParams.creator"
                    filterable
                    multiple
                    :max-tag-count="1"
                  >
                    <Option
                      v-for="(item, index) in users"
                      :value="item.id"
                      :label="item.real_name"
                      :key="index"
                    ></Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
          </Form>
          <Table
            :columns="testcaseColumns"
            :data="testcaseData"
            border
            size="small"
            style="margin-top: 5px"
            :max-height="500"
            :tooltip-max-width="500"
          >
            <template slot-scope="{ row }" slot="action">
              <Button
                size="small"
                type="text"
                style="color: #2d8cf0"
                @click="selectTestcase(row)"
                >选择</Button
              >
            </template>
            <template slot-scope="{ row }" slot="api">
              <span slot="content">{{ row.api.name }}</span>
            </template>
            <template slot-scope="{ row }" slot="url">
              <Tooltip placement="bottom" transfer :max-width="500">
                <div slot="content" style="white-space: normal">
                  {{
                    row.url +
                    (row.request_params ? "?" + row.request_params : "")
                  }}
                </div>
                {{
                  row.url + (row.request_params ? "?" + row.request_params : "")
                }}
              </Tooltip>
            </template>
            <template slot-scope="{ row }" slot="level">
              <div class="levelDiv">
                <div
                  :class="
                    'levelSelect-prefix levelOption-' + row.level.toLowerCase()
                  "
                ></div>
                <div>{{ levels[row.level] }}</div>
              </div>
            </template>
            <template slot-scope="{ row }" slot="status">
              <Icon
                size="24"
                :color="statusColor[row.status]"
                type="ios-leaf"
              />
            </template>
          </Table>
          <Page
            transfer
            :total="page.total"
            :current="page.current"
            :page-size="page.pageSize"
            :page-size-opts="page.pageSizeOpts"
            size="small"
            show-elevator
            show-sizer
            show-total
            prev-text="上一页"
            next-text="下一页"
            style="margin-top: 15px"
            @on-change="change"
            @on-page-size-change="pageSizeChange"
          />
        </div>
      </CollapseTransition>
    </Card>
    <Card title="组织用例 (拖动调整顺序)" :dis-hover="true">
      <div slot="extra">
        <Form inline :label-width="150" :model="testsuiteForm">
          <FormItem label="从已有场景添加用例">
            <div style="display: flex">
              <Select
                clearable
                filterable
                transfer
                v-model="testsuiteForm.id"
                placeholder="请选择场景"
              >
                <Option
                  v-for="item in testsuiteData"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </Select>
              <Button type="primary" @click="copyTestsuite2testcase"
                >添加</Button
              >
              <Button
                type="primary"
                @click="createExtMethod"
                class="card-extra-item"
                >添加扩展方法</Button
              >
            </div>
          </FormItem>
        </Form>
      </div>
      <Table
        :columns="selectedTestcaseColumns"
        :data="selectedTestcaseData"
        border
        draggable
        size="small"
        style="margin-top: 5px"
        :tooltip-max-width="500"
        @on-drag-drop="dragDropSelectedTestcaseData"
        :span-method="handleSpan"
      >
        <template
          slot-scope="{ row, index }"
          slot="testcase_name|ext_method_name"
        >
          <tooltip
            transfer
            max-width="500"
            style="width: 100%"
            placement="bottom"
            :content="selectedTestcaseData[index].testcase_name"
            v-if="row.type == 'HTTP_API'"
          >
            <Input
              placeholder="请输入用例名称"
              v-model="selectedTestcaseData[index].testcase_name"
              style="width: 100%"
              @on-change="changeTestcaseName(index)"
            />
          </tooltip>
          <tooltip
            transfer
            max-width="500"
            style="width: 100%"
            placement="bottom"
            :content="selectedTestcaseData[index].ext_method_name"
            v-if="row.type == 'EXT_METHOD'"
          >
            <Input
              placeholder="请输入扩展方法名称"
              v-model="selectedTestcaseData[index].ext_method_name"
              style="width: 100%"
            />
          </tooltip>
        </template>
        <template slot-scope="{ row, index }" slot="loop_count">
          <InputNumber
            readonly
            :min="1"
            :precision="0"
            style="width: 100%"
            v-model="selectedTestcaseData[index].loop_count"
          ></InputNumber>
        </template>
        <template slot-scope="{ row, index }" slot="api|ext_method">
          <tooltip
            transfer
            max-width="500"
            placement="bottom"
            :content="row.testcase.api.name"
            v-if="row.type == 'HTTP_API'"
            >{{ row.testcase.api.name }}</tooltip
          >
          <AutoComplete
            transfer
            placeholder="请输入扩展方法"
            v-else-if="row.type == 'EXT_METHOD'"
            v-model="selectedTestcaseData[index].ext_method"
            @on-focus="focusExtMethod(index)"
            @on-change="changeExtMethod"
          >
            <Option
              v-for="item in extMethodData"
              :value="item.ext_method"
              :key="item.id"
              class="autocomplete-option"
            >
              <span>{{ item.name }}</span>
              <span>{{ item.ext_method }}</span>
            </Option>
          </AutoComplete>
        </template>
        <template slot-scope="{ row }" slot="url">
          <Tooltip placement="bottom" transfer :max-width="500">
            <div slot="content" style="white-space: normal">
              {{
                row.url + (row.request_params ? "?" + row.request_params : "")
              }}
            </div>
            {{ row.url + (row.request_params ? "?" + row.request_params : "") }}
          </Tooltip>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <i-switch
            v-model="row.is_execute"
            size="large"
            true-color="#19be6b"
            false-color="#ff4949"
            @on-change="
              selectedTestcaseData[index]['is_execute'] = row.is_execute
            "
          >
            <span slot="open">执行</span>
            <span slot="close">跳过</span>
          </i-switch>
          <Button
            size="small"
            type="text"
            style="color: #2d8cf0"
            @click="editSelectedTestcase(row, index)"
            >编辑</Button
          >
          <Button
            size="small"
            type="text"
            style="color: #ed4014"
            @click="removeSelectedTestcase(row, index)"
            >移除</Button
          >
        </template>
      </Table>
    </Card>
    <div slot="footer">
      <Button type="default" @click="handleOrganizeTestcaseCancel">取消</Button>
      <Button type="primary" @click="handleOrganizeTestcaseSubmit">确定</Button>
    </div>
    <TestsuiteTestcaseEdit
      :testsuiteTestcaseEdit.sync="testsuiteTestcaseEdit"
      :testcase="selectedTestcase"
      @updateSelectedTestcase="updateSelectedTestcase"
    >
    </TestsuiteTestcaseEdit>
    <TestsuiteExtMethodEdit
      :testsuiteExtMethodEdit.sync="testsuiteExtMethodEdit"
      :extMethod="selectedExtMethod"
      @updateSelectedExtMethod="updateSelectedExtMethod"
    ></TestsuiteExtMethodEdit>
  </Modal>
</template>

<script>
import { treeToArray } from "@/libs/custom.utils";
import { getModuleNames } from "@/api/HttpAutoTestService/module";
import { getApiNames } from "@/api/HttpAutoTestService/api";
import { getTestcases } from "@/api/HttpAutoTestService/testcase";
import {
  createTestsuite2Testcase,
  getTestsuite2Testcases,
} from "@/api/HttpAutoTestService/testsuite2testcase";
import { getExtMethodNames } from "@/api/HttpAutoTestService/ext-method";
import { getTestsuiteNames } from "@/api/HttpAutoTestService/testsuite";
import { getUserNames } from "@/api/HttpAutoTestService/user";
import TestsuiteTestcaseEdit from "./testsuite-testcase-edit";
import TestsuiteExtMethodEdit from "./testsuite-ext-method-edit";
import SelectTree from "_c/select-tree";
import CollapseTransition from "_c/collapse-transition/collapse-transition.js";

export default {
  name: "testsuite2testcase",
  components: {
    TestsuiteTestcaseEdit,
    TestsuiteExtMethodEdit,
    SelectTree,
    CollapseTransition,
  },
  props: {
    organizeTestcase: {
      type: Boolean,
      default: false,
    },
    project: {
      type: Object,
      default: () => {
        return {};
      },
    },
    testsuite: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      showMore: true,
      testsuiteExtMethodEdit: false,
      testsuiteTestcaseEdit: false,
      statusColor: {
        INITIAL: "#2db7f5",
        PASS: "#19be6b",
        FAIL: "#ed4014",
      },
      searchParams: {
        name: "",
        module: "",
        api: [],
        creator: [],
      },
      testcaseColumns: [
        {
          title: "操作",
          slot: "action",
          align: "center",
          width: 120,
          fixed: "left",
          renderHeader: (h, params) => {
            return h(
              "div",
              {
                style: {
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                },
              },
              [
                h("div", "操作"),
                h(
                  "Button",
                  {
                    props: {
                      tpye: "text",
                      size: "small",
                      ghost: true,
                    },
                    style: {
                      color: "#2b85e4",
                      marginLeft: "5px",
                    },
                    on: {
                      click: this.selectAllTestcase,
                    },
                  },
                  "全选"
                ),
              ]
            );
          },
        },
        {
          title: "用例名称",
          key: "name",
          width: 350,
          fixed: "left",
          tooltip: true,
        },
        {
          title: "接口",
          slot: "api",
          width: 200,
          ellipsis: true,
        },
        {
          title: "请求URL",
          slot: "url",
          width: 300,
          ellipsis: true,
        },
        {
          title: "Headers参数",
          key: "headers",
          width: 350,
          ellipsis: true,
        },
        {
          title: "Body参数类型",
          key: "request_data_type",
          width: 120,
          align: "center",
        },
        {
          title: "Body参数",
          key: "request_data",
          width: 350,
          ellipsis: true,
        },
        {
          title: "期望结果",
          key: "expect_result",
          width: 350,
          ellipsis: true,
        },
        {
          title: "创建时间",
          key: "create_time",
          width: 160,
          align: "center",
        },
        {
          title: "更新时间",
          key: "update_time",
          width: 160,
          align: "center",
        },
        {
          title: "重要级别",
          slot: "level",
          align: "center",
          width: 85,
          fixed: "right",
        },
        {
          title: "状态",
          slot: "status",
          align: "center",
          width: 65,
          fixed: "right",
        },
      ],
      testcaseData: [],
      selectedTestcaseColumns: [
        {
          title: "用例名称|扩展方法名称",
          slot: "testcase_name|ext_method_name",
          width: 310,
          align: "center",
          fixed: "left",
        },
        {
          title: "循环次数",
          slot: "loop_count",
          width: 120,
          align: "center",
        },
        {
          title: "接口名称",
          slot: "api|ext_method",
          width: 200,
          ellipsis: true,
        },
        {
          title: "请求URL",
          slot: "url",
          width: 300,
          ellipsis: true,
        },
        {
          title: "Headers参数",
          key: "headers",
          width: 350,
          ellipsis: true,
        },
        {
          title: "Body参数类型",
          key: "request_data_type",
          width: 120,
          align: "center",
        },
        {
          title: "Body参数",
          key: "request_data",
          width: 350,
          ellipsis: true,
        },
        {
          title: "期望结果",
          key: "expect_result",
          width: 350,
          ellipsis: true,
        },
        {
          title: "操作",
          slot: "action",
          align: "center",
          width: 185,
          fixed: "right",
          renderHeader: (h, params) => {
            return h(
              "div",
              {
                style: {
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                },
              },
              [
                h("div", "操作"),
                h(
                  "Button",
                  {
                    props: {
                      tpye: "text",
                      size: "small",
                      ghost: true,
                    },
                    style: {
                      color: "#ed4014",
                      marginLeft: "5px",
                    },
                    on: {
                      click: () => {
                        this.selectedTestcaseData = [];
                      },
                    },
                  },
                  "清空"
                ),
              ]
            );
          },
        },
      ],
      selectedTestcaseData: [],
      testsuiteData: [],
      extMethodData: [],
      originExtMethodData: [],
      levels: {
        LOW: "低",
        NORMAL: "中",
        HIGH: "高",
        HIGHER: "更高",
      },
      moduleData: [],
      moduleSelectTreeData: [],
      apis: [],
      users: [],
      page: {
        current: 1,
        total: 0,
        pageSize: 30,
        pageSizeOpts: [10, 30, 50, 100, 200],
      },
      selectedExtMethod: {
        index: null,
        ext_method_name: "",
        type: "",
        ext_method: "",
        expect_result: "",
      },
      selectedTestcase: {
        index: null,
        type: "",
        testcase_name: "",
        url: "",
        headers: "",
        request_data_type: "",
        request_params: "",
        request_data: "",
        expect_result: "",
      },
      testsuiteForm: { id: "" },
    };
  },
  mounted() {
    getExtMethodNames()
      .then((res) => {
        const data = res.data;
        this.extMethodData = data;
        this.originExtMethodData = data;
      })
      .catch((err) => {
        this.$Modal.error({
          title: "系统异常，请联系管理员……",
          content: JSON.stringify(err),
          closable: true,
        });
      });
    // 获取用户
    getUserNames()
      .then((res) => {
        this.users = res.data;
      })
      .catch((err) => {
        this.$Modal.error({
          title: "系统异常，请联系管理员……",
          content: JSON.stringify(err),
          closable: true,
        });
      });
  },
  watch: {
    organizeTestcase(val) {
      if (val) {
        this.searchParams.creator = [this.$store.state.user.id];
        this.search();
      }
    },
    project(val) {
      if (this.showOrganizeTestcaseModal && val) {
        // 获取模块
        this.getModuleNames();
        // 获取接口
        this.getApiNames();
        // 获取已有场景
        this.getTestsuiteNames();
      }
    },
    testsuite(val) {
      if (this.showOrganizeTestcaseModal && val) {
        setTimeout(() => {
          getTestsuite2Testcases({ testsuite: val.id })
            .then((res) => {
              this.selectedTestcaseData = res.data;
            })
            .catch((err) => {});
        }, 1000);
      }
    },
  },
  computed: {
    showOrganizeTestcaseModal: {
      get() {
        return this.organizeTestcase;
      },
      set(val) {
        this.$emit("update:organizeTestcase", val);
        this.$emit("update:project", {});
        this.$emit("update:testsuite", {});
      },
    },
    projectTestsuiteName() {
      return `项目：${this.project.name} | 场景：${this.testsuite.name}`;
    },
  },
  methods: {
    reset() {
      this.searchParams = {
        name: "",
        module: "",
        api: [],
        creator: [],
      };
      this.getApiNames();
      this.search();
    },
    search(page) {
      let data = {
        project: this.project.id,
        name: this.searchParams.name,
        module: this.searchParams.module,
        api: this.searchParams.api.toString(),
        creator: this.searchParams.creator.toString(),
        page: 1,
        page_size: this.page.pageSize,
        ordering: "create_time",
      };
      if (typeof page == "number") {
        data.page = page;
      }
      this.page.current = data.page;

      getTestcases(data)
        .then((res) => {
          const data = res.data;
          this.testcaseData = data.results;
          this.page.total = data.count;
          if (data.next === null) {
            this.page.current = Math.ceil(this.page.total / this.page.pageSize);
          }
          if (data.previous === null) {
            this.page.current = 1;
          }
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },
    // 获取模块
    getModuleNames() {
      getModuleNames({ project: this.project.id })
        .then((res) => {
          let data = res.data;
          let moduleSelectTreeData = data.map((item) => {
            return {
              value: item.id,
              title: item.name,
              parent: item.parent,
              expand: false,
            };
          });

          let arrayToTree = require("array-to-tree");
          this.moduleSelectTreeData = arrayToTree(moduleSelectTreeData, {
            parentProperty: "parent",
            childrenProperty: "children",
            customID: "value",
          });
          // 存放模块树转成的数组数据
          this.moduleData = treeToArray(this.moduleSelectTreeData);
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },
    // 获取接口
    getApiNames() {
      let data = {
        project: this.project.id,
        module: this.searchParams.module,
      };
      getApiNames(data)
        .then((res) => {
          const data = res.data;
          let apis = [];
          let apiIds = [];
          data.forEach((item) => {
            let api = {
              id: item.id,
              name: item.name,
            };
            apis.push(api);
            if (this.searchParams.api.includes(item.id)) {
              apiIds.push(item.id);
            }
          });
          this.apis = apis;
          this.searchParams.api = apiIds;
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },
    // 获取已有场景
    getTestsuiteNames() {
      getTestsuiteNames({ project: this.project.id })
        .then((res) => {
          this.testsuiteData = res.data;
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },
    // 选择请求接口
    selectChangeApi() {},
    // 选择接口所属模块
    selectChangeModule(hideVal, showVal) {
      if (this.searchParams.module != "") {
        let selectedModule = this.moduleData.filter((item) => {
          return item.value == this.searchParams.module;
        });
        selectedModule = treeToArray(selectedModule[0]);
        let selectedModuleIds = selectedModule.map((item) => {
          return item.value;
        });
        this.searchParams.module = selectedModuleIds.toString();
      }
      this.getApiNames();
    },
    // 调整用例执行顺序
    dragDropSelectedTestcaseData(oldIndex, newIndex) {
      let movedRow = this.selectedTestcaseData[oldIndex];
      this.selectedTestcaseData.splice(oldIndex, 1);
      this.selectedTestcaseData.splice(newIndex, 0, movedRow);
    },
    change(val) {
      this.page.current = val;
      this.search(val);
    },
    pageSizeChange(val) {
      this.page.pageSize = val;
      this.search();
    },
    // 选择单个测试用例
    selectTestcase(row) {
      let selectedTestcase = {
        testsuite_id: this.testsuite.id,
        testsuite_name: this.testsuite.name,
        testcase_name: row.name,
        testcase: {
          id: row.id,
          api: row.api,
        },
        url: row.url,
        headers: row.headers,
        request_params: row.request_params,
        request_data_type: row.request_data_type,
        request_data: row.request_data,
        expect_result: row.expect_result,
        type: "HTTP_API",
        is_execute: true,
        loop_count: 1,
      };
      this.selectedTestcaseData.push(selectedTestcase);
    },
    // 选择全部测试用例
    selectAllTestcase() {
      this.testcaseData.forEach((item) => {
        let selectedTestcase = {
          testsuite_id: this.testsuite.id,
          testsuite_name: this.testsuite.name,
          testcase_name: item.name,
          testcase: {
            id: item.id,
            api: item.api,
          },
          url: item.url,
          headers: item.headers,
          request_params: item.request_params,
          request_data_type: item.request_data_type,
          request_data: item.request_data,
          expect_result: item.expect_result,
          type: "HTTP_API",
          is_execute: true,
          loop_count: 1,
        };
        this.selectedTestcaseData.push(selectedTestcase);
      });
    },
    // 移除测试用例
    removeSelectedTestcase(row, index) {
      this.selectedTestcaseData.splice(index, 1);
    },
    // 编辑选中的测试用例
    editSelectedTestcase(row, index) {
      if (row.type === "HTTP_API") {
        let url = row.url;
        let request_params = row.request_params;
        if (request_params) {
          url = url + "?" + request_params;
        }
        this.selectedTestcase = {
          index: index,
          type: row.type,
          testcase_name: row.testcase_name,
          url: url,
          request_data_type: row.request_data_type,
          request_params: "",
          headers: row.headers,
          request_data: row.request_data,
          expect_result: row.expect_result,
        };
        this.testsuiteTestcaseEdit = true;
      } else if (row.type === "EXT_METHOD") {
        let { ext_method_name, ext_method, expect_result, type } = row;
        this.selectedExtMethod = {
          ext_method_name,
          ext_method,
          expect_result,
          type,
        };
        let data = {
          index: index,
        };
        Object.assign(this.selectedExtMethod, data);
        this.testsuiteExtMethodEdit = true;
      }
    },
    handleOrganizeTestcaseSubmit() {
      let testsuite2testcase = {
        testsuite_id: this.testsuite.id,
        data: [],
      };
      if (this.selectedTestcaseData.length > 0) {
        testsuite2testcase.data = this.selectedTestcaseData.map(
          (item, index) => {
            if (typeof item.loop_count !== "number" || item.loop_count < 1) {
              item.loop_count = 1;
            }
            if (item.type == "HTTP_API") {
              return {
                testsuite_id: this.testsuite.id,
                testsuite_name: this.testsuite.name,
                testcase_id: item.testcase.id,
                testcase_name: item.testcase_name,
                url: item.url,
                headers: item.headers,
                request_params: item.request_params,
                request_data_type: item.request_data_type,
                request_data: item.request_data,
                expect_result: item.expect_result,
                is_execute: item.is_execute,
                type: item.type,
                loop_count: item.loop_count,
                sort: index,
                update_testcase: item.update_testcase,
              };
            } else if (item.type == "EXT_METHOD") {
              return {
                testsuite_id: this.testsuite.id,
                testsuite_name: this.testsuite.name,
                ext_method_name: item.ext_method_name,
                ext_method: item.ext_method,
                is_execute: item.is_execute,
                expect_result: item.expect_result,
                type: item.type,
                loop_count: item.loop_count,
                sort: index,
              };
            }
          }
        );
      }
      createTestsuite2Testcase(testsuite2testcase)
        .then((res) => {
          if (res.status === 201) {
            this.$Message.info("用例组织成功");
            this.handleOrganizeTestcaseCancel();
          } else {
            this.$Message.error("用例组织失败");
          }
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },
    // 复制测试场景用例
    copyTestsuite2testcase() {
      if (this.testsuiteForm.id) {
        getTestsuite2Testcases({ testsuite: this.testsuiteForm.id })
          .then((res) => {
            this.selectedTestcaseData = this.selectedTestcaseData.concat(
              res.data
            );
            this.testsuiteForm = { id: "" };
          })
          .catch((err) => {});
      } else {
        this.$Message.info("请先选择场景……");
      }
    },
    // 添加扩展方法
    createExtMethod() {
      let extMethod = {
        type: "EXT_METHOD",
        ext_method: "",
        expect_result: {
          output: [],
          validate: [],
        },
        loop_count: 1,
        is_execute: true,
      };
      this.selectedTestcaseData.push(extMethod);
    },
    handleOrganizeTestcaseCancel() {
      this.showOrganizeTestcaseModal = false;
      this.selectedTestcaseData = [];
      this.testcaseData = [];
      this.testsuiteForm = { id: "" };
      this.$emit("initTestsuiteTable");
    },
    handleSpan({ row, column, rowIndex, columnIndex }) {
      if (row.type === "EXT_METHOD") {
        if (columnIndex === 2) {
          return {
            rowspan: 1,
            colspan: 5,
          };
        } else if (columnIndex >= 2 && columnIndex <= 6) {
          return {
            rowspan: 1,
            colspan: 0,
          };
        } else {
          return {
            rowspan: 1,
            colspan: 1,
          };
        }
      }
    },
    focusExtMethod(index) {
      let value = this.selectedTestcaseData[index].ext_method;
      if (value) {
        this.extMethodData = this.originExtMethodData.filter((item) => {
          return item.ext_method.indexOf(value) !== -1;
        });
      } else {
        this.extMethodData = this.originExtMethodData;
      }
    },
    changeExtMethod(value) {
      if (!value) {
        this.extMethodData = this.originExtMethodData;
      } else {
        this.extMethodData = this.originExtMethodData.filter((item) => {
          return item.ext_method.indexOf(value) !== -1;
        });
      }
    },
    changeTestcaseName(index) {
      if (!this.selectedTestcaseData[index].testcase_name) {
        this.$Message.error("用例名称不能为空");
      }
    },
    // 更新扩展方法
    updateSelectedExtMethod(extMethod) {
      let index = extMethod.index;
      this.selectedTestcaseData[index].ext_method_name =
        extMethod.ext_method_name;
      this.selectedTestcaseData[index].ext_method = extMethod.ext_method;
      this.selectedTestcaseData[index].expect_result = extMethod.expect_result;
    },
    // 更新用例
    updateSelectedTestcase(testcase) {
      let index = testcase.index;
      this.selectedTestcaseData[index].testcase_name = testcase.testcase_name;
      this.selectedTestcaseData[index].url = testcase.url;
      this.selectedTestcaseData[index].headers = testcase.headers;
      this.selectedTestcaseData[index].request_data_type =
        testcase.request_data_type;
      this.selectedTestcaseData[index].request_params = testcase.request_params;
      this.selectedTestcaseData[index].request_data = testcase.request_data;
      this.selectedTestcaseData[index].expect_result = testcase.expect_result;
      this.selectedTestcaseData[index].update_testcase =
        testcase.update_testcase;
    },
  },
};
</script>

<style scoped>
.levelDiv {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.levelSelect-prefix {
  width: 15px;
  height: 15px;
  border-radius: 100%;
}
.levelOption-low {
  background-color: #2db7f5;
}
.levelOption-normal {
  background-color: #19be6b;
}
.levelOption-high {
  background-color: #ff9900;
}
.levelOption-higher {
  background-color: #ed4014;
}
.autocomplete-option {
  display: flex;
  justify-content: space-between;
}
</style>
